﻿using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement;
using System.Transactions;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 审批或反审销售订单处理器
    /// </summary>
    public class AppOrUnappSalesOrderHandler : IRequestHandler<AppOrUnappSalesOrderCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<SalesOrder> salesOrderRepository;
        private readonly ILogger<AppOrUnappSalesOrderHandler> logger;

        public AppOrUnappSalesOrderHandler(
            IBaseRepository<SalesOrder> salesOrderRepository,
            ILogger<AppOrUnappSalesOrderHandler> logger)
        {
            this.salesOrderRepository = salesOrderRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 处理审批或反审销售订单请求
        /// </summary>
        /// <param name="request">审批或反审请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public Task<APIResult<bool>> Handle(AppOrUnappSalesOrderCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();

            try
            {
                logger.LogInformation("开始处理销售订单状态变更，订单ID：{OrderId}，目标状态：{TargetStatus}", request.Id, request.OrderStatus);

                // 1. 验证状态值是否正确
                if (request.OrderStatus != "开立" && request.OrderStatus != "审批")
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "请选择正确状态，状态只能是'开立'或'审批'";
                    logger.LogWarning("销售订单状态值不正确，ID：{OrderId}，状态值：{Status}", request.Id, request.OrderStatus);
                    return Task.FromResult(result);
                }

                // 2. 检查销售订单是否存在
                var salesOrder = salesOrderRepository.GetModel(request.Id);
                if (salesOrder == null)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "销售订单不存在或已被删除";
                    logger.LogWarning("销售订单不存在或已被删除，ID：{OrderId}", request.Id);
                    return Task.FromResult(result);
                }

                // 3. 检查当前状态是否与目标状态相同
                if (salesOrder.OrderStatus == request.OrderStatus)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = $"当前状态已是{request.OrderStatus}";
                    logger.LogWarning("销售订单当前状态已经是目标状态，ID：{OrderId}，状态：{Status}", request.Id, request.OrderStatus);
                    return Task.FromResult(result);
                }

                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        // 4. 更新销售订单状态
                        salesOrder.OrderStatus = request.OrderStatus;
                        
                        // 如果是审批操作，记录审批信息
                        if (request.OrderStatus == "审批")
                        {
                            salesOrder.AuditDate = DateTime.Now;
                            salesOrder.Auditor = "system"; // 这里应该从当前用户上下文获取
                        }
                        else
                        {
                            // 如果是反审操作，清除审批信息
                            salesOrder.AuditDate = null;
                            salesOrder.Auditor = null;
                        }

                        var updateResult = salesOrderRepository.Update(salesOrder);
                        if (updateResult <= 0)
                        {
                            throw new InvalidOperationException("销售订单状态更新失败");
                        }
                        
                        logger.LogInformation("销售订单状态更新成功，ID：{OrderId}，新状态：{NewStatus}", salesOrder.Id, salesOrder.OrderStatus);

                        // 5. 提交事务
                        transaction.Complete();

                        result.Code = APIEnums.Success;
                        result.Data = true;
                        result.Msg = $"销售订单{(request.OrderStatus == "审批" ? "审批" : "反审")}成功";
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "销售订单状态更新过程中发生错误：{Message}", ex.Message);
                        result.Code = APIEnums.Error;
                        result.Msg = $"销售订单{(request.OrderStatus == "审批" ? "审批" : "反审")}失败";
                        result.Data = false;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "销售订单状态更新失败：{Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = $"销售订单{(request.OrderStatus == "审批" ? "审批" : "反审")}失败";
                result.Data = false;
            }

            return Task.FromResult(result);
        }
    }
}
